import '../App.css';
import './Aside.css';
import axios from 'axios';
import { Input } from '@arco-design/web-react';
import { IconSettings,IconPlusCircle,IconMinusCircle,IconSearch } from '@arco-design/web-react/icon';
import { Image,Modal } from '@arco-design/web-react';
import AllInOne from '../../assets/all-in-one-a9c88adf.svg';
import {saveSetting as saveSettingApi} from '../../api/all'

import chatallsImg from '../../assets/chatalls.png'
import KeFu from '../../assets/kefu.jpeg'

import UserIcon from '../../assets/user.svg';
import UserIconWhite from '../../assets/user_white.svg';
import KefuIcon from '../../assets/kefu.svg';
import KefuIconWhite from '../../assets/kefu_white.svg';
import SettingIcon from '../../assets/setting.svg';
import SettingIconWhite from '../../assets/setting_white.svg';
import JuheTwoIcon from '../../assets/2.svg'
import JuheTwoIconCheck from '../../assets/2_.svg'
import JuheThreeIcon from '../../assets/3.svg'
import JuheThreeIconCheck from '../../assets/3_.svg'
import JuheFourIcon from '../../assets/4.svg'
import JuheFourIconCheck from '../../assets/4_.svg'
import JuheSixIcon from '../../assets/6.svg'
import JuheSixIconCheck from '../../assets/6_.svg'

import { NavLink } from "react-router-dom";

import { useState, useEffect, useRef } from 'react'
import { useLocation } from "react-router";

import Theme from './Theme'

// import {userInfo} from '../../api/all'


import {
  useRecoilValue,
  useRecoilState,
} from 'recoil';

import { currentAiChat,robotList,currentAiChatState, settingInfo } from './store'

import {getSetting as ajaxSetting,userInfo as getUser,getRobot} from '../../api/all'

let vipType = {
  6:'月度会员',
  7:'年度会员'
}

let juhe = [{
  num:2,
  icon:JuheTwoIcon,
  activeIcon:JuheTwoIconCheck
},{
  num:3,
  icon:JuheThreeIcon,
  activeIcon:JuheThreeIconCheck
},{
  num:4,
  icon:JuheFourIcon,
  activeIcon:JuheFourIconCheck
},{
  num:6,
  icon:JuheSixIcon,
  activeIcon:JuheSixIconCheck
}]

function Aside() {
  const location = useLocation()
  const currentChat = useRecoilValue(currentAiChatState);
  // const setting = useRecoilValue(settingInfoState);

  const [text, setText] = useRecoilState(currentAiChat);
  const [collapseStatus, setCollapseStatus] = useState(false)
  const [list, setList] = useRecoilState(robotList)
  const [visible, setVisible] = useState(false);
  const [config, setConfig] = useRecoilState(settingInfo)

  const [userInfo, setUserInfo] = useState(null)
  const [curModel,setCurModel] = useState(2)
  const [listFilter, setListFilter] = useState([])

  const [juheNum,setJuheNum] = useState(2)


  const themeRef = useRef(null)

  const collapse = () => {
    setCollapseStatus(!collapseStatus)
  }

  const tabClick = (item) => {
    if(curModel === 2){
      setText(item);
    }
  }
  useEffect(() => {
    // userInfo().then((res)=>{
    // })
    getList()
  }, [])
  useEffect(() => {
    getSetting()
  }, [list])


  useEffect(() => {
    if(list.length>0){
      if(location.pathname == '/all'){
        // tabClick({
        //   id: 0,
        //   icon: AllInOne,
        //   name: 'All-In-One'
        // })
      }else{
        let index_robot_id = config.index_robot_id
        let index = list.findIndex((obj)=>{
          return obj.id === index_robot_id
        })
        tabClick(list[index])
      }
    }
  }, [config,list])

  const getList = ()=>{
    getRobot().then(res => {
      res && res.result?.map( (obj,idx) => {
          obj.icon = obj.logo || AllInOne
          obj.active = idx === 1 ? true : false
        })
        setList(res.result.reverse())
        // let li = res.result
        // tabClick(li[0])
    });
  }

  const getSetting = ()=>{
    if(localStorage.getItem('token')){
      ajaxSetting().then(res => {
        console.log(res)
        setConfig(res?.result)
        setJuheNum(res?.result?.together)
      });
      getUserInfo()
    }
  }

  const getUserInfo = ()=>{
    getUser().then((res)=>{
      let user = res.result
      setUserInfo(user)
    })
  }

  const userInfoText = (userInfo)=>{
    let str = ''
    let className = ''
    if(userInfo){
      str = userInfo.is_vip === 1 ? vipType[userInfo.vip_id]:'免费会员'
      className = userInfo.vip_id == 6 ? 'month_vip' : (userInfo.vip_id == 7 ? 'year_vip' : 'free_vip')
    }else{
      str = '免费会员'
      className = 'free_vip'
    }
    return {
      str,
      className}
  }

  const searchModel = (value) => {
    let copylist = JSON.parse(JSON.stringify(list))
    let filterlist = copylist.filter((obj)=>{
      return obj.name.indexOf(value) > -1
    })
    setListFilter(filterlist)
  }

  const tabHtml = (item) => {
    return (
      <NavLink to={curModel==1?'/all':'/'} key={item.id} onClick={(e) => tabClick(item)} className="rounded-[10px] w-full pl-3 flex gap-3 items-center shrink-0 bg-white text-primary-text tab" title={item.name} style={{ '--tw-bg-opacity': (curModel == 2 && item.id == currentChat.id) ? '1' : '0.4',background: (curModel == 2 && currentChat.id == item.id) || (curModel == 1 && config.together_ids.indexOf(item.id)>-1) ? '#F4F4F4' : '#fff',padding:'15px' }}>
        <div className='tab_left'><img alt='' src={item.icon} className="w-5 h-5" /><span className="font-medium text-sm muxingname">{item.name}</span></div>{curModel == 1 && (config.together_ids.indexOf(item.id)>-1?<IconMinusCircle onClick={()=>{minusRobot(item)}} style={{fontSize: '16px'}}/>:<IconPlusCircle onClick={()=>{plusRobot(item)}} style={{fontSize: '16px'}}/>)}
      </NavLink>
    )
  }

  const minusRobot = (item) => {
    let together_ids = config.together_ids.split(",").filter(val => val != item.id);
    sumitData({user_id: userInfo.id, index_robot_id: config.index_robot_id, together:juheNum, together_ids:together_ids.join(","), id: 22})
  }

  const plusRobot = (item) => {
    console.log(config,userInfo,item)
    let together_ids = config.together_ids.split(",")
    together_ids.push(item.id)
    sumitData({user_id: userInfo.id, index_robot_id: config.index_robot_id, together:juheNum, together_ids:together_ids.join(","), id: 22})
  }

  const sumitData = (params) => {
    saveSettingApi(params).then(res => {
      if(res.code === 0){
        // setConfig(params)
        sessionStorage.setItem("recentsetting", 1);
        getSetting()
      }
    },error => {
        console.log("get request failed:",error);
    });
  }

  const clickJuhe = ((num)=>{
    setJuheNum(num)
    let together_ids = config.together_ids.split(",")
    sumitData({user_id: userInfo.id, index_robot_id: config.index_robot_id, together:num, together_ids:together_ids.join(","), id: 22})
  })

  return (
    <>
      <div className="aside">
        <div className='aside-fixed'>
          {!collapseStatus && <img  src={chatallsImg} alt="" />}
          {/* {collapseStatus && <img className="miniLogo"  src={Logo} alt="" />} */}
          {/* <img alt='' src={Collapse} onClick={collapse} className={collapseStatus ? "w-6 h-6 cursor-pointer my-5 rotate-180 collapse1" : "w-6 h-6 cursor-pointer my-5 self-end collapse"} /> */}
          {/* <img alt='' src={collapseStatus ? minimalLogo : Logo} className={collapseStatus ? "w-[30px]" : "w-[79px] self-start"} /> */}
        </div>
        <div className="flex flex-col gap-[13px] overflow-y-auto scrollbar-none list" style={{ width: collapseStatus ? '42px' : '216px' }}>
          <div className='rounded-[10px] w-full flex flex-row text-primary-text choose_type'>
            <NavLink to={'/all'} className='model' onClick={() => setCurModel(1)} style={{background: curModel == 1 ? '#ffffff' : '' }}>聚合模型</NavLink>
            <NavLink to={'/'} className='model' onClick={() => setCurModel(2)} style={{background: curModel == 2 ? '#ffffff' : '' }}>单个模型</NavLink>
          </div>
          <div>选择模型</div>
          <div className='rounded-[10px] w-full flex flex-row text-primary-text search_type'>
            <div className='icon_search_box'>
              <IconSearch className='icon_search'/>
            </div>
            <Input className='search_input'  onChange={(value) => {
                searchModel(value)
              }}  style={{ width: '100%' }} allowClear  placeholder='搜索模型' />
          </div>
          {
            curModel==1 && <div className='rounded-[10px] w-full flex flex-row text-primary-text juhe_type'>
            {
              juhe.map((item)=>{
                return <div className='icon_juhe' onClick={()=>{clickJuhe(item.num)}} style={{background:juheNum == item.num ?'#f4f4f4':''}}>
                  <img className='' src={ juheNum == item.num ? item.activeIcon : item.icon } alt=''/>
                </div>
              })
            }
          </div>
          }
        {/* <NavLink to={'/all'} key={0} onClick={(e) => tabClick({
          id: 0,
          icon: AllInOne,
          name: 'All-In-One'
        })} className="rounded-[10px] w-full pl-3 flex flex-row gap-3 items-center shrink-0 py-[11px] bg-white text-primary-text dark:bg-primary-blue" title={'All-In-One'} style={{ '--tw-bg-opacity': currentChat.id == 0 ? '1' : '0.4',background: currentChat.id == 0 ? '#F4F4F4' : '#fff' }}>
          <img alt='' src={AllInOne} className="w-5 h-5" /><span className="font-medium text-sm" style={{ whiteSpace: 'nowrap' }}>All-In-One</span>
        </NavLink> */}
          {
            listFilter.length>0 ? listFilter.map(item => {
              return tabHtml(item)
            })
            :
            list.map(item => {
                return tabHtml(item)
            })
          }
        </div>
        <div className="mt-auto pt-2">
          <hr style={{ display: collapseStatus ? 'none' : 'block' }} className="border-[#ffffff4d]" />
          <div style={{ display: collapseStatus ? 'none' : 'flex-block' }} className="level-box">
            <NavLink to="/buy" style={{display: 'inline-block',width:'138px',height:'40px'}}>
              <div className={`level cursor-pointer ${userInfoText(userInfo).className}`}>
                {/* <img alt='' src={premium} className="w-8 h-8" /> */}
                <span className="text-white font-semibold text-base">{
                  userInfoText(userInfo).str
                }</span>
              </div>
            </NavLink>
          </div>
          <div className="flex flex-row bot_nav">
            <NavLink to="/premium" style={{ display: collapseStatus ? 'none' : 'block' }} className='rounded-[10px]'>
              <div className="p8px rounded-[10px] w-fit cursor-pointer hover:opacity-80">
                <img alt='' src={UserIcon} className="nav_icon" />
              </div>
            </NavLink>
            <NavLink style={{ display: collapseStatus ? 'none' : 'block' }} className='rounded-[10px]' onClick={()=>{setVisible(true)}} >
              <div className="p8px rounded-[10px] w-fit cursor-pointer hover:opacity-80">
                <img alt='' src={KefuIcon} className="nav_icon" />
              </div>
            </NavLink>
            <NavLink  to="/setting" className='rounded-[10px]'>
              <div className="p8px rounded-[10px] w-fit cursor-pointer hover:opacity-80">
                <img alt='' src={SettingIcon} className="nav_icon" />
              </div>
            </NavLink>
          </div>
        </div>
      </div>


      <Modal
        title='联系客服'
        visible={visible}
        onCancel={() => setVisible(false)}
        footer={null}
        autoFocus={false}
        focusLock={true}
      >
        <div className='kefu-box'>
        <Image
          width={400}
          src={KeFu}
          alt='kefu'
        />
        </div>
      </Modal>

      <Theme ref={themeRef}/>
    </>
  );
}

export default Aside;
